const financePaymentMethod = require('../../../../utils/finance-payment-method');
Page({
  data: {
    paymentMethodList: [],
    limit: 10,
    newName: '',
    showEditModal: false,
    editName: '',
    editIndex: -1,
  },
  async onLoad() {
    await this.initData();
  },
  async initData() {
    const res = await financePaymentMethod.paymentMethodInit();
    const listRes = await financePaymentMethod.getAllMethods();
    this.setData({
      paymentMethodList: listRes || [],
      limit: res.limit || 10,
      newName: '',
      showEditModal: false,
      editName: '',
      editIndex: -1,
    });
  },
  onNewNameInput(e) {
    this.setData({ newName: e.detail.value });
  },
  async onAdd() {
    const name = this.data.newName.trim();
    if (!name) return wx.showToast({ title: '请输入名称', icon: 'none' });
    if (name.length > 10) return wx.showToast({ title: '最多10个字', icon: 'none' });
    if (this.data.paymentMethodList.length >= this.data.limit) return wx.showToast({ title: '已达上限', icon: 'none' });
    wx.showLoading({ title: '新建中...' });
    try {
      await financePaymentMethod.paymentMethodAdd({ name });
      wx.hideLoading();
      await this.initData();
    } catch (e) {
      wx.hideLoading();
      wx.showToast({ title: (e && e.data && e.data.msg) || '新建失败', icon: 'none' });
    }
  },
  onEdit(e) {
    const idx = e.currentTarget.dataset.index;
    const item = this.data.paymentMethodList[idx];
    this.setData({ showEditModal: true, editName: item.name, editIndex: idx });
  },
  onEditNameInput(e) {
    this.setData({ editName: e.detail.value });
  },
  async onEditConfirm() {
    const idx = this.data.editIndex;
    const name = this.data.editName.trim();
    if (!name) return wx.showToast({ title: '请输入新名称', icon: 'none' });
    if (name.length > 10) return wx.showToast({ title: '最多10个字', icon: 'none' });
    wx.showLoading({ title: '编辑中...' });
    try {
      await financePaymentMethod.paymentMethodEdit({ id: this.data.paymentMethodList[idx].id, name });
      wx.hideLoading();
      await this.initData();
    } catch (e) {
      wx.hideLoading();
      wx.showToast({ title: (e && e.data && e.data.msg) || '编辑失败', icon: 'none' });
    }
  },
  onEditCancel() {
    this.setData({ showEditModal: false, editName: '', editIndex: -1 });
  },
  async onDelete(e) {
    const idx = e.currentTarget.dataset.index;
    const item = this.data.paymentMethodList[idx];
    wx.showModal({
      title: '删除支付方式',
      content: '确定要删除该支付方式吗？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' });
          try {
            await financePaymentMethod.aymentMethodDelete(item.id);
            wx.hideLoading();
            await this.initData();
          } catch (e) {
            wx.hideLoading();
            wx.showToast({ title: (e && e.data && e.data.msg) || '删除失败', icon: 'none' });
          }
        }
      }
    });
  },
});


